<?php
declare (strict_types=1);

namespace app\index\middleware;

use app\service\MemberService;
use think\facade\Cookie;


use app\middleware\Response;

class Auth
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {

        $uid = session("mid");
        $email = Cookie::get("email");
        if (empty($uid)) {
            if ($email) {
                $email = h_decrypt($email);
                $service = app()->make(MemberService::class);
                $member = $service->getOne(["email" => $email], "status,id");
                if (!$member) {
                    return redirect('/login');
                }
                if ($member->status == MemberService::STATE_DENY) {
                    return redirect('/login');
                }
                $uid = $member->id;
                session("mid", $uid);
            } else {
                if ($request->isAjax()) {
                    return json(["code" => 1, "msg" => "登录失效"]);
                }
                return redirect('/login');
            }
        }
        $request->uid = $uid;
        return $next($request);
    }
}
